package cn.sc.summer.core.config.redis;

import cn.hutool.core.util.StrUtil;
import cn.sc.summer.core.util.SpringSecurityUserUtil;
import io.lettuce.core.resource.ClientResources;
import io.lettuce.core.resource.DefaultClientResources;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.lang.Nullable;

import java.util.Objects;

/**
 * 类名：redis键的序列化配置配置类，一般会在redis键前加上对应园区ID
 *
 * @author a-xin
 * @date 2023/9/27 10:20
 */
@Slf4j
//@Configuration
public class RedisConnectConfig extends StringRedisSerializer {

    /**
     * 配置redis连接池断链
     */
    @Bean(destroyMethod = "shutdown")
    public ClientResources clientResources() {
        return DefaultClientResources.create();
    }

    public static final String PREFIX = "T%s:";

    /**
     * redis key序列化
     *
     * @param redisKey object to serialize. Can be {@literal null}.
     * @return 序列化后的键
     */
    @Override
    public byte[] serialize(@Nullable String redisKey) {
        String cachePrefix = "";
        if (Objects.nonNull(SpringSecurityUserUtil.getLoginUser()) && !SpringSecurityUserUtil.hasLoginStatus()) {
            cachePrefix = String.format(PREFIX, SpringSecurityUserUtil.getLoginUser().getTenantId());
        }
        return super.serialize(cachePrefix + redisKey);
    }

    /**
     * redis key反序列化
     *
     * @param bytes object binary representation. Can be {@literal null}.
     * @return 序列化后的键
     */
    @Override
    public String deserialize(@Nullable byte[] bytes) {
        String cachePrefix = "";
        if (Objects.nonNull(SpringSecurityUserUtil.getLoginUser()) && !SpringSecurityUserUtil.hasLoginStatus()) {
            cachePrefix = String.format(PREFIX, SpringSecurityUserUtil.getLoginUser().getTenantId());
        }
        if (StrUtil.isNotBlank(cachePrefix)) {
            return Objects.requireNonNull(super.deserialize(bytes)).replaceFirst(cachePrefix, "");
        } else {
            return super.deserialize(bytes);
        }
    }

}
